from bitstring import BitStream, BitArray
from utils import BYTE, WORD, BCD, formatter
from utils import FLAG_CODE_1078 as FLAG_CODE


def parse_msg(bitstream: BitStream):
    parse_result = {}

    # 标识位校验
    flag = bitstream.read("uint:32")
    if flag == FLAG_CODE:
        pass
    else:
        raise ValueError("Invalid flag code")

    # 消息头解析
    head_fmt = formatter(f"""
                bin:2=v,
                bin:1=p,
                bin:1=x,
                bin:4=cc,
                hex:1=m,
                hex:7=pt,
                uint:{WORD}=pkt_no,
                hex:{BCD * 6}=sim_no,
                hex:{BYTE}=logical_channel_no,
                hex:4=data_type,
                hex:4=pkt_sep_flag,
                hex:{BYTE * 8}=timestamp,
                hex:{WORD}=last_i_frame_interval,
                hex:{WORD}=last_frame_interval,
                uint:{WORD}=data_length,
                bytes=data,
                """)
    head = bitstream.readlist(head_fmt)
    if head[0] != '10' or head[1] != '0' or head[2] != '0' or head[3] != '0001':
        raise ValueError("Invalid header")

    parse_result.setdefault("m", head[4])
    parse_result.setdefault("pt", head[5])
    parse_result.setdefault("pkt_no", head[6])
    parse_result.setdefault("sim_no", head[7])
    parse_result.setdefault("logical_channel_no", head[8])
    parse_result.setdefault("data_type", head[9])
    parse_result.setdefault("pkt_sep_flag", head[10])
    parse_result.setdefault("timestamp", head[11])
    parse_result.setdefault("last_i_frame_interval", head[12])
    parse_result.setdefault("last_frame_interval", head[13])
    parse_result.setdefault("data_length", head[14])
    parse_result.setdefault("data", head[15])

    return parse_result
